package com.qiantu.phone.ui.dialog;

import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.DensityUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.ui.adapter.RoomFloorDialogAdapter;
import com.lxj.xpopup.core.AttachPopupView;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class AreaSelectDialog extends AttachPopupView implements View.OnClickListener {
    public static final int TYPE_SCENE = 1;
    public static final int TYPE_DEVICE = 2;
    public static final int TYPE_LINKAGE = 3;
    public static final int TYPE_PANEL_Binging = 4;
    public static final int TYPE_SMART = 5;
    public static final int AVAILABLE_DEVICE = 12;
    public static final int TRIGGER_DEVICE = 13;

    private TextView selectAreas;
    private ImageView close;
    private AppCompatTextView allArea;
    private boolean allAreaIsSelect = true;
    private AppCompatTextView commonArea;
    private boolean commonAreaIsSelect = false;
    private RecyclerView floorRoomList;
    private TextView save;
    private RoomFloorDialogAdapter mAdapter;
    private Map<String, RoomBean> mSelectArea = new LinkedHashMap<>();
    private Map<String, RoomBean> mSaveArea = new LinkedHashMap<>();
    private List<FloorBean> mFloorBeans;
    //1 场景 2 设备
    private int type;
    //初始场景或者设备数量
    private int mInitCount;
    private int deviceCategory;

    public AreaSelectDialog(@NonNull Context context, int type) {
        super(context);
        this.type = type;
    }

    public AreaSelectDialog(@NonNull Context context, int type, int deviceCategory) {
        super(context);
        this.type = type;
        this.deviceCategory = deviceCategory;
    }

    public void setInitCount(int count) {
        this.mInitCount = count;
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.area_select_ly;
    }

    // 执行初始化操作，比如：findView，设置点击，或者任何你弹窗内的业务逻辑
    @Override
    protected void onCreate() {
        super.onCreate();
        selectAreas = (TextView) findViewById(R.id.select_areas);
        close = (ImageView) findViewById(R.id.close);
        close.setOnClickListener(this);
        allArea = (AppCompatTextView) findViewById(R.id.all_area);
        allArea.setOnClickListener(this::onClick);
        commonArea = (AppCompatTextView) findViewById(R.id.common_area);
        commonArea.setOnClickListener(this);
        floorRoomList = (RecyclerView) findViewById(R.id.floor_room_list);
        save = (TextView) findViewById(R.id.save);
        save.setOnClickListener(this);

        save.setText(R.string.ok);
        allArea.setText(type == TYPE_DEVICE ? R.string.all_device : R.string.unlimited_area);
//        commonArea.setText(type == TYPE_SCENE ? R.string.common_scene : R.string.common_device);

        floorRoomList.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new RoomFloorDialogAdapter(getContext()) {
            @Override
            public void onSelectChanged(Map<String, RoomBean> selectBean) {
                allArea.setSelected(false);
//                setTitle(null);
                getSelectedCountAsync(new GetSelectedCountCallback() {
                    @Override
                    public void onResult(int count) {
                        setTitle(count);
                    }
                });
            }
        };
        mAdapter.setData(mFloorBeans);
        floorRoomList.setAdapter(mAdapter);
    }

    @Override
    protected void onShow() {
        super.onShow();
    }

    @Override
    protected void beforeShow() {
        super.beforeShow();
        initSelectState();
    }

    private void initSelectState() {
        mSelectArea.clear();
        mSelectArea.putAll(mSaveArea);
        mAdapter.setSelectMap(mSelectArea);
        allArea.setSelected(allAreaIsSelect);
        commonArea.setSelected(commonAreaIsSelect);
        setTitle(mInitCount);
    }

    public AreaSelectDialog setFloorBeans(List<FloorBean> data) {
        mFloorBeans = data;
        if (mAdapter != null) {
            mAdapter.setData(data);
        }
        return this;
    }

    // 设置最大宽度，看需要而定
    @Override
    protected int getMaxWidth() {
        return super.getMaxWidth();
    }

    // 设置最大高度，看需要而定
    @Override
    protected int getMaxHeight() {
        return super.getMaxHeight();
    }

    /**
     * 弹窗的宽度，用来动态设定当前弹窗的宽度，受getMaxWidth()限制
     *
     * @return
     */
    protected int getPopupWidth() {
        return DensityUtils.getScreenWidth(getContext()) - 2 * DensityUtils.dip2px(getContext(), 16);
    }

    /**
     * 弹窗的高度，用来动态设定当前弹窗的高度，受getMaxHeight()限制
     *
     * @return
     */
    protected int getPopupHeight() {
        return DensityUtils.dip2px(getContext(), 388);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.save) {
            mSaveArea.clear();
            mSaveArea.putAll(mSelectArea);
            allAreaIsSelect = allArea.isSelected();
            commonAreaIsSelect = commonArea.isSelected();
            if (type == TYPE_SCENE) {
                onSave(getAllSceneFormSelectArea());
            } else if(type == TYPE_PANEL_Binging){
                getDevicesAsync(new GetDevicesCallback() {
                    @Override
                    public void onResult(List<DeviceBean> devices) {
                        onPanelBingingSave(devices,getAllSceneFormSelectArea());
                    }
                });
            }else if(type == TYPE_SMART){
                onSmartSave(getAllSceneFormSelectArea(),allArea.isSelected(),commonArea.isSelected(),mSelectArea);
            } else{
                getDevicesAsync(new GetDevicesCallback() {
                    @Override
                    public void onResult(List<DeviceBean> devices) {
                        onConfirm(devices);
                    }
                });
            }
            dismiss();
        } else if (id == R.id.close) {
            dismiss();
        } else if (id == R.id.all_area) {
            if (!allArea.isSelected()) {
                allArea.setSelected(true);
                commonArea.setSelected(false);
                mAdapter.clearSelected();
                mAdapter.setCanBeEmpty(commonArea.isSelected());
//                setTitle(null);
            }
            getSelectedCountAsync(new GetSelectedCountCallback() {
                @Override
                public void onResult(int count) {
                    setTitle(count);
                }
            });
        } else if (id == R.id.common_area) {
            if (mSelectArea == null || mSelectArea.isEmpty()) {
                if (!commonArea.isSelected()) {
                    commonArea.setSelected(true);
                    allArea.setSelected(false);
                    mAdapter.setCanBeEmpty(true);
//                    setTitle(null);
                }
            } else {
                commonArea.setSelected(!commonArea.isSelected());
                mAdapter.setCanBeEmpty(commonArea.isSelected());
//                setTitle(null);
            }
            getSelectedCountAsync(new GetSelectedCountCallback() {
                @Override
                public void onResult(int count) {
                    setTitle(count);
                }
            });
        }
    }

    private void getDevicesAsync(GetDevicesCallback callback){
        if(getContext() != null && getContext() instanceof AppActivity){
            ((AppActivity)getContext()).showDialog();
        }
        Observable.create(new ObservableOnSubscribe<List<DeviceBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<DeviceBean>> emitter) throws Exception {
                List<DeviceBean> devices = getAllDeviceFormSelectArea();
                emitter.onNext(devices);
            }
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<DeviceBean>>() {
                    @Override
                    public void accept(List<DeviceBean> devices) throws Exception {
                        if(getContext() instanceof AppActivity){
                            ((AppActivity)getContext()).hideDialog();
                        }
                        callback.onResult(devices);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                });
    }

    public interface GetDevicesCallback{
        void onResult(List<DeviceBean> devices);
    }

    private int calculateSelectedCount(){
        int selectedCount = 0;
        if (type == TYPE_SCENE) {
            List<SceneBean> selected = getAllSceneFormSelectArea();
            selectedCount = selected.size();
        } else {
            List<DeviceBean> selected = getAllDeviceFormSelectArea();
            selectedCount = selected.size();
        }
        return selectedCount;
    }

    private void getSelectedCountAsync(GetSelectedCountCallback callback){
        if(getContext() != null && getContext() instanceof AppActivity){
            ((AppActivity)getContext()).showDialog();
        }
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                int count = calculateSelectedCount();
                emitter.onNext(count);
            }
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer count) throws Exception {
                        if(getContext() instanceof AppActivity){
                            ((AppActivity)getContext()).hideDialog();
                        }
                        callback.onResult(count);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                });
    }

    public interface GetSelectedCountCallback{
        void onResult(int count);
    }

    public List<SceneBean> getAllSceneFormSelectArea() {
        if (allArea.isSelected()) {
            return LLSceneDBManager.getInstance(getContext()).getAll();
        }
        List<SceneBean> sences = new ArrayList<>();
        List<String> roomSerialNos = new ArrayList<>();
        List<String> floorSerialNos = new ArrayList<>();
        if (commonArea.isSelected()) {
            sences.addAll(LLSceneDBManager.getInstance(getContext()).getCommonScenes());
        }

        if (mSelectArea != null){
            for (String roomSerialNo : mSelectArea.keySet()) {
                RoomBean roomBean = mSelectArea.get(roomSerialNo);
                if(roomBean.getRoomSerialNo().equals(roomBean.getFloorSerialNo())){
                    floorSerialNos.add(roomBean.getFloorSerialNo());
                }else{
                    roomSerialNos.add(roomBean.getRoomSerialNo());
                }
            }
        }
        sences.addAll(LLSceneDBManager.getInstance(getContext()).getScenesForFloorSerialNos(floorSerialNos));
        sences.addAll(LLSceneDBManager.getInstance(getContext()).getScenesForRoomSerialNos(roomSerialNos));
        return sences;
    }

    public List<DeviceBean> getAllDeviceFormSelectArea() {
        if (allArea.isSelected()) {
            switch (deviceCategory){
                case AVAILABLE_DEVICE:
                    return LLDeviceDBManager.getInstance(getContext()).getAvailableDevices();
                case TRIGGER_DEVICE:
                    return LLDeviceDBManager.getInstance(getContext()).getTriggerDevices();
                default:
                    return LLDeviceDBManager.getInstance(getContext()).getAll();
            }
        }
        List<String> roomSerialNos = new ArrayList<>();
        if (commonArea.isSelected()) {
            roomSerialNos.add(RoomBean.ROOM_COMMON_SERIALNO);
        }
        if(mSelectArea != null){
            for (String roomSerialNo : mSelectArea.keySet()) {
                roomSerialNos.add(roomSerialNo);
            }
        }
        switch (deviceCategory){
            case AVAILABLE_DEVICE:
                return LLDeviceDBManager.getInstance(getContext()).getAvailableDevicesByRoomSerialNos(roomSerialNos);
            case TRIGGER_DEVICE:
                return LLDeviceDBManager.getInstance(getContext()).getTriggerDevicesByRoomSerialNos(roomSerialNos);
            default:
                return LLDeviceDBManager.getInstance(getContext()).getDevicesByRoomSerialNos(roomSerialNos);
        }
    }

    public void setTitle(Integer size) {
        StringBuilder result = new StringBuilder();
        if (allArea.isSelected()) {
            result.append(type ==  TYPE_DEVICE ? getResources().getString(R.string.all_device) : getResources().getString(R.string.unlimited_area));
        } else {
            if (commonArea.isSelected()) {
                result.append(getResources().getString(R.string.common));
            }
            if (mSelectArea != null && !mSelectArea.isEmpty()) {
                for (String roomSerialNo : mSelectArea.keySet()) {
                    if (result.length() == 0) {
                        result.append(mSelectArea.get(roomSerialNo).getRoomName());
                    } else {
                        result.append("、").append(mSelectArea.get(roomSerialNo).getRoomName());
                    }
                }
            }
        }
//        if (size != null) {
//            result.append(" (").append(size).append(")");
//        } else {
//            result.append(" (").append(mInitCount).append(")");
//        }
        selectAreas.setText(result.toString());
    }

    public String getTitle() {
        return selectAreas.getText().toString();
    }

    public boolean isAllAreaIsSelect() {
        return allAreaIsSelect;
    }

    public boolean isCommonAreaIsSelect() {
        return commonAreaIsSelect;
    }

    public Map<String, RoomBean> getSelectArea() {
        return mSelectArea;
    }

    public void onSave(List<SceneBean> result) {
    }

    public void onConfirm(List<DeviceBean> result) {
    }

    public void onPanelBingingSave(List<DeviceBean> deviceBeans,List<SceneBean> sceneBeans) {
    }

    public void onSmartSave(List<SceneBean> sceneBeans,boolean allSelect,boolean commonSelect,Map<String, RoomBean> selectArea) {
    }
}
